package com.ruoyi.flowable.util;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class URLEncoderUtils {

    /**
     * 完整URL编码处理
     */
    public static String encodeFullUrl(String url) {
        try {
            // 检查是否包含中文
            if (!containsChinese(url)) {
                return url;
            }

            // 使用Java的URL类进行处理
            java.net.URL urlObj = new java.net.URL(url);

            String protocol = urlObj.getProtocol();
            String host = urlObj.getHost();
            int port = urlObj.getPort();
            String path = urlObj.getPath();
            String query = urlObj.getQuery();

            // 编码路径
            String encodedPath = encodePath(path);

            // 重建URL
            StringBuilder encodedUrl = new StringBuilder();
            encodedUrl.append(protocol).append("://").append(host);
            if (port != -1) {
                encodedUrl.append(":").append(port);
            }
            encodedUrl.append(encodedPath);
            if (query != null) {
                encodedUrl.append("?").append(query);
            }

            return encodedUrl.toString();

        } catch (Exception e) {
            System.err.println("URL编码失败: " + e.getMessage());
            return url;
        }
    }

    /**
     * 编码路径部分
     */
    private static String encodePath(String path) {
        if (path == null || path.isEmpty()) return "";

        String[] segments = path.split("/");
        StringBuilder encodedPath = new StringBuilder();

        for (String segment : segments) {
            if (!segment.isEmpty()) {
                if (encodedPath.length() > 0) encodedPath.append("/");
                encodedPath.append(URLEncoder.encode(segment, StandardCharsets.UTF_8));
            }
        }

        return encodedPath.length() > 0 ? "/" + encodedPath.toString() : "";
    }

    /**
     * 检查字符串是否包含中文
     */
    private static boolean containsChinese(String str) {
        if (str == null) return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断字符是否为中文
     */
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
    }
}
